import { useState, useEffect } from "react";
import { showError, showSuccess } from 'utils/common';
import { useTheme } from "@mui/material/styles";
import {
  IconAddressBook,
  IconNote,
  IconPlus,
} from "@tabler/icons-react";
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Divider,
  Box,
  IconButton,
  Button,
  Stack,
  FormControl,
  InputLabel,
  InputAdornment,
  OutlinedInput,
} from "@mui/material";

import CloseIcon from '@mui/icons-material/Close';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import { DataGrid} from '@mui/x-data-grid';
import { GridActionsCellItem } from '@mui/x-data-grid-pro';

import { API } from "utils/api";
import { Container } from "@mui/system";
require("dayjs/locale/zh-cn");

const ITEMS_PER_PAGE = 5;
const ipRegexp = /^(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([1-9]|[1-2]\d|3[0-2]))?$/

export default function IpWhiteListModal({ open, tokenId, onCancel, onOk }) {
  const columns = [
    {
      field: 'ip',
      headerName: 'IPv4/CIDR',
      width: 200,
      editable: true,
    },
    {
      field: 'note',
      headerName: '备注',
      width: 500,
      editable: true,
    },
    {
      field: 'actions',
      headerName: '操作',
      type: 'actions',
      width: 150,
      getActions: (params) => [
        <GridActionsCellItem icon={<DeleteIcon />} label="Delete" onClick={()=>{
          handleDelWhiteList(params.id)
        }} sx={{ color: 'error.main' }}/>,
      ],
    },
  ];
  const theme = useTheme();
  const grey500 = theme.palette.grey[500];


  const [whiteLists, setWhiteLists] = useState([]);
  const [total, setTotal] = useState(0);
  const [ipaddr, setIpaddr] = useState('');
  const [isIpaddr, setIsIpaddr] = useState(true);
  const [note, setNote] = useState('');
  const [activePage, setActivePage] = useState(0);
  const [searching, setSearching] = useState(false);

  const loadTokenWhiteLists = async (startIdx) => {
    setSearching(true);
    const res = await API.get(`/api/token/white_list/${parseInt(tokenId)}/?p=${startIdx}&ps=${ITEMS_PER_PAGE}`);
    const { success, message, data } = res.data;
    if (success) {
      if (startIdx === 0) {
        setWhiteLists(data.white_lists);
      } else {
        let newWhiteLists = [...whiteLists];
        newWhiteLists.splice(startIdx * ITEMS_PER_PAGE, data.white_lists.length, ...data.white_lists);
        setWhiteLists(newWhiteLists);
      }
      setTotal(data.total)
    } else {
      showError(message);
    }
    setSearching(false);
  };

  useEffect(() => {
    if (tokenId) {
      loadTokenWhiteLists(0)
        .then()
        .catch((reason) => {
          showError(reason);
        });
    }
  }, [tokenId]);

  useEffect(() => {
    loadTokenWhiteLists(0)
      .then()
      .catch((reason) => {
        showError(reason);
      });
  }, []);

  const handlePageModelChange = (params) => {
    //console.log(params)
    //params.page,params.pageSize

    //const newState = { ...pageState, pageModel: params }
    //setState(asPath, newState)
    (async () => {
      if (params.page === Math.ceil(whiteLists.length / ITEMS_PER_PAGE)) {
        // In this case we have to load more data and then append them.
        await loadTokenWhiteLists(params.page );
      }
      setActivePage(params.page);
    })();
}

const handleAddWhiteList = () => {
  (async () => {
    let values ={
      ip: ipaddr,
      note: note,
    } 
    let res = await API.post(`/api/token/white_list/${parseInt(tokenId)}/`, values);
    const { success, message } = res.data;
    if (success) {
        showSuccess("添加白名单成功！");
        loadTokenWhiteLists(0)
          .then()
          .catch((reason) => {
            showError(reason);
          });
    } else {
      showError(message);
    }
  })();
}
const handleUpdateWhiteList = (field,tokenWhiteList,value) => {
  (async () => {
    if (field=="note"){
      tokenWhiteList.note = value
    }
    if (field=="ip"){
      if (!ipRegexp.test(value)){
        showError("IPv4/CIDR：格式错误")
        loadTokenWhiteLists(activePage)
          .then()
          .catch((reason) => {
            showError(reason);
          });
        return
      }
      tokenWhiteList.ip = value
    }

    let res = await API.put(`/api/token/white_list/${parseInt(tokenId)}/`, tokenWhiteList);
    const { success, message } = res.data;
    if (success) {
        showSuccess("修改白名单成功！");
        loadTokenWhiteLists(activePage)
          .then()
          .catch((reason) => {
            showError(reason);
          });
    } else {
      showError(message);
    }
  })();
}
const handleDelWhiteList = (id) => {
  (async () => {
    let res = await API.delete(`/api/token/white_list/${parseInt(tokenId)}/${parseInt(id)}`);
    const { success, message } = res.data;
    if (success) {
        showSuccess("删除白名单成功！");
        loadTokenWhiteLists(activePage)
          .then()
          .catch((reason) => {
            showError(reason);
          });
    } else {
      showError(message);
    }
  })();
}

  return (
    <Dialog open={open} onClose={onCancel} fullWidth maxWidth={"md"}>
      <DialogTitle
        sx={{
          margin: "0px",
          fontWeight: 700,
          lineHeight: "1.55556",
          padding: "24px",
          fontSize: "1.125rem",
        }}
      >
        {"IP白名单管理"}
      </DialogTitle>
      <IconButton
          aria-label="close"
          onClick={onCancel}
          sx={{
            position: 'absolute',
            right: 8,
            top: 8,
            color: (theme) => theme.palette.grey[500],
          }}
        >
          <CloseIcon />
        </IconButton>
      <Divider />
      <DialogContent>
        <Box sx={{ width: '100%' ,height:'400px'}}>
          <DataGrid
            rows={whiteLists}
            columns={columns}
            initialState={{
              pagination: {
                paginationModel: {
                  pageSize: ITEMS_PER_PAGE,
                },
              },
              pinnedColumns: {
                left: ['name'],
                right: ['actions']
              }
            }}
            onPaginationModelChange={handlePageModelChange}
            onCellEditStop={(params,event)=>{
              if (event.target){
                handleUpdateWhiteList(params.field,params.row,event.target.value)
              }
            }}
            pageSizeOptions={[5]}
            autoHeight = {false}
            //checkboxSelection
            disableRowSelectionOnClick
            rowCount={total}
          />
        </Box>
     </DialogContent>
     <Divider />
     <DialogContent>
      <Stack
        direction={{ xs: "column", sm: "row" }}
        spacing={{ xs: 3, sm: 2, md: 4 }}
        padding={"24px"}
        paddingBottom={"0px"}
      >
        <FormControl>
          <InputLabel htmlFor="white_list-ip_cidr-label">IPv4/CIDR</InputLabel>
          <OutlinedInput
            id="ip_addr"
            name="ip_addr"
            sx={{
              minWidth: "100%",
            }}
            label="IPv4/CIDR"
            value={ipaddr}
            onChange={(event)=>{
              setIpaddr(event.target.value)
              setIsIpaddr(ipRegexp.test(event.target.value))
            }}
            error={!isIpaddr}
            placeholder="IPv4/CIDR"
            startAdornment={
              <InputAdornment position="start">
                <IconAddressBook stroke={1.5} size="20px" color={grey500} />
              </InputAdornment>
            }
          />
        </FormControl>
        <FormControl>
          <InputLabel htmlFor="white_list-note-label">备注</InputLabel>
          <OutlinedInput
            id="note"
            name="note"
            sx={{
              minWidth: "100%",
            }}
            label="备注"
            value={note}
            onChange={(event)=>{
              setNote(event.target.value)
            }}
            placeholder="备注"
            startAdornment={
              <InputAdornment position="start">
                <IconNote stroke={1.5} size="20px" color={grey500} />
              </InputAdornment>
            }
          />
        </FormControl>
        <FormControl>
        <Button
          variant="contained"
          color="primary"
          sx={{
            "margin": "6px",
            "flex": "auto",
          }}
          onClick={() => {
              if (isIpaddr && ipaddr !== ''){
                handleAddWhiteList();
              }else{
                showError("IPv4/CIDR：格式错误");
              }
            }
          }
          startIcon={<IconPlus />}
        >
          添加白名单
        </Button>
        </FormControl>
      </Stack>
     </DialogContent>
    </Dialog>
  );
}